package lookie.swing.tree.model.util;

import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.ExpandVetoException;

import lookie.swing.tree.model.LazyTreeNode;
import lookie.swing.tree.model.TreeNodeProvider;

public class LazyTreeNodeWillExpandListener implements TreeWillExpandListener {

	private TreeNodeProvider provider;

	public LazyTreeNodeWillExpandListener(TreeNodeProvider provider) {
		super();
		this.provider = provider;
	}

	public TreeNodeProvider getProvider() {
		return provider;
	}

	public void treeWillCollapse(TreeExpansionEvent event)
			throws ExpandVetoException {

	}

	public void treeWillExpand(TreeExpansionEvent event)
			throws ExpandVetoException {
		Object lastComponent = event.getPath().getLastPathComponent();
		if (lastComponent instanceof LazyTreeNode) {
			LazyTreeNode node = (LazyTreeNode) lastComponent;
			if (!node.isLoaded()) {
				node.fill(provider.getChildren(node));
			}
		}
	}

}
